/* eslint-disable array-bracket-spacing */
/* eslint-disable no-dupe-class-members */
/* eslint-disable indent */
'use strict'

const Service = require('egg').Service
const dayjs = require('dayjs')
const { Op } = require('sequelize')

// 信息要返回的字段
const attributes = ['id', 'm_bid', 'pid', 'upmachine_time', 'computer_name', 'area_name', 'consume_amount']
const member_attributes = ['id', 'mid', 'openid', 'unionid', 'phone', 'nickname', 'avatar', 'sex', 'birthday', 'register_time', 'last_login_time', 'level_name', 'subscribe', 'subscribe_time', 'pid', 'card_id', 'balance', 'recharge_amount', 'consume_time', 'week_count', 'count', 'status']
const place_attributes = ['barname', 'barcode']

class OnlineMemberService extends Service {

    // 查询所有列表
    async getOnlineMemberList(params) {
        const { model, helper } = this.ctx
        const currentPage = params?.pageIndex ?? 1
        const pageSize = params?.pageSize ?? 200

        const where = {}
        if (params.pid !== undefined && params.pid != null) {
            where.pid = params.pid
        }
        return await model.OnlineMember.findAndCountAll({
            where,
            offset: (currentPage - 1) * pageSize, // 计算分页偏移量
            limit: pageSize,
            attributes,
            include: [
                {
                    model: model.Place,
                    // as: 'place',
                    attributes: place_attributes
                },
                {
                    model: model.Member,
                    // as: 'member',
                    attributes: member_attributes
                }
            ],
            order: [
                ['computer_name', 'ASC'],
                ['upmachine_time', 'DESC']
            ]
        })
            .then(async result => {
                if (result) {
                    return {
                        list: result.rows,
                        total: result.count
                    }
                }
                helper.failed(1008, null, '查询会员列表失败')
                return false
            })
            .catch(async error => {
                if (error?.original?.sqlMessage) {
                    helper.failed(1001, null, error?.original?.sqlMessage)
                } else if (error?.errors) {
                    helper.failed(1001, null, JSON.stringify(error.errors))
                } else {
                    helper.failed(1001, null, JSON.stringify(error))
                }
                return false
            })
    }

    // 换机操作
    async createChangeMachine(params) {
        const { model, helper, logger } = this.ctx
        let flag = 0
        // 使用事务
        const t = await model.transaction()
        try {
            // 会员信息
            const [member, isCreated] = await model.Member.findOrCreate({
                where: {
                    mid: params.mid,
                    pid: params.pid
                },
                defaults: {
                    ...params,
                    register_time: dayjs().format('YYYY-MM-DD HH:mm:ss')
                },
                transaction: t
            })
            if (!isCreated && member) {
                const res = await member.update({
                    ...params
                }, {
                    transaction: t
                })
                // console.log('修改会员', res)
            }
            flag = 1

            // 在线会员信息
            let result = await model.OnlineMember.findOne({
                where: {
                    pid: params.pid,
                    m_bid: member.id
                },
                transaction: t,
                attributes,
                include: [
                    {
                        model: model.Member,
                        // as: 'member',
                        attributes: member_attributes
                    }
                ]
            })
            if (result) {
                // console.log("在线会员存在", result)
                await result.update({
                    computer_name: params?.computer_to !== '' ? params.computer_to : null,
                    area_name: params?.area_to !== '' ? params.area_to : null
                }, {
                    transaction: t
                })
            } else {
                result = await model.OnlineMember.create({
                    pid: params.pid,
                    m_bid: member.id,
                    upmachine_time: params.upmachine_time,
                    computer_name: params?.computer_to !== '' ? params.computer_to : null,
                    area_name: params?.area_to !== '' ? params.area_to : null
                }, {
                    transaction: t
                })
            }
            flag = 2

            await t.commit()
            flag = 3

            const online = result.toJSON()
            const res = await member.toJSON()
            res.computer_name = params?.computer_to ? params.computer_to : ''
            res.area_name = params?.area_to ? params.area_to : ''
            res.computer_from = params?.computer_from ? params.computer_from : ''
            res.area_from = params?.area_from ? params.area_from : ''
            res.upmachine_time = online?.upmachine_time ? online.upmachine_time : ''
            return res
        } catch (error) {
            await t.rollback() // 回滚

            if (error?.original?.sqlMessage) {
                logger.error(`换机操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${error?.original?.sqlMessage}`)
                helper.failed(1001, null, error?.original?.sqlMessage)
            } else if (error?.errors[0]?.message) {
                logger.error(`换机操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${error.errors[0]?.message}`)
                helper.failed(1001, null, error.errors[0]?.message)
            } else {
                logger.error(`换机操作失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${JSON.stringify(error)}`)
                helper.failed(1001, null, JSON.stringify(error))
            }

            return false
        }
    }

    // 同步在线会员
    async syncOnlineMember(params) {
        const { model, helper, logger } = this.ctx
        let flag = 0
        // console.log('参数', params)
        // 使用事务
        const t = await model.transaction()
        try {
            const ids = []
            const results = []
            for (const item of params.members) {
                // 会员信息
                let register_time = dayjs().format('YYYY-MM-DD HH:mm:ss')
                if (item?.register_time && item.register_time !== '') {
                    register_time = item.register_time
                }

                const tmp_attributes = {}
                if (item?.birthday && item.birthday !== '') {
                    tmp_attributes.birthday = item.birthday
                }
                if (item?.sex && item.sex !== 0) {
                    tmp_attributes.sex = item.sex
                }
                if (item?.level_name && item.level_name !== '') {
                    tmp_attributes.level_name = item.level_name
                }
                if (item?.card_id && item.card_id !== '') {
                    tmp_attributes.card_id = item.card_id
                }

                const [member, isCreated] = await model.Member.findOrCreate({
                    where: {
                        pid: params.pid,
                        mid: item.xy_user_id
                    },
                    defaults: {
                        mid: item.xy_user_id,
                        register_time,
                        ...tmp_attributes
                    },
                    transaction: t
                })
                flag = 0.5
                if (!isCreated && member) {
                    const res = await member.update({
                        ...tmp_attributes
                        // register_time
                    }, {
                        transaction: t
                    })
                }
                flag = 1

                // 在线会员列表
                await model.OnlineMember.findOne({
                    where: {
                        pid: params.pid,
                        m_bid: member.id,
                        computer_name: item.client_name
                    },
                    transaction: t
                }).then(async result => {
                    if (result) {
                        const update_where = {}
                        if (item?.upmachine_time && item.upmachine_time !== '') { update_where.upmachine_time = item.upmachine_time }
                        if (item?.area_name && item.area_name !== '') { update_where.area_name = item.area_name }
                        if (item?.consume_amount && item.consume_amount !== '') { update_where.consume_amount = item.consume_amount }
                        await result.update(update_where, {
                            transaction: t
                        })
                        ids.push(result.dataValues.id)
                        // console.log('result1111: ', result.dataValues)
                    } else {
                        await model.OnlineMember.create({
                            pid: params.pid,
                            m_bid: member.id,
                            upmachine_time: item.upmachine_time,
                            computer_name: item.client_name,
                            area_name: item.area_name,
                            consume_amount: item?.consume_amount
                        }, {
                            transaction: t
                        })
                            .then(async result => {
                                console.log('result22222: ', result)
                                ids.push(result.dataValues.id)
                            })
                            .catch(error => {
                                // console.log('添加在线会员失败: ', error)
                                logger.error(`添加在线会员失败   pid:[${params.pid}] mid:[${item.xy_user_id}] ${JSON.stringify(error)}`)
                            })
                    }
                }).catch(error => {
                    // console.log('查询在线会员失败: ', error)
                    logger.error(`查询在线会员失败   pid:[${params.pid}] mid:[${item.xy_user_id}] ${JSON.stringify(error)}`)
                })
                flag = 2
            }
            flag = 3
            console.log('ids: ', ids)

            // 删除其他多余在线会员
            await await model.OnlineMember.destroy({
                where: {
                    id: {
                        [Op.notIn]: ids
                    },
                    pid: params.pid
                },
                transaction: t
            })
            flag = 4

            // 查询在线会员列表
            await model.OnlineMember.findAll({
                where: {
                    pid: params.pid
                },
                include: [
                    {
                        model: model.Member,
                        // as: 'member',
                        attributes: member_attributes
                    }
                ],
                transaction: t
            }).then(async members => {
                for (const member of members) {
                    results.push({
                        ...member.toJSON().member,
                        computer_name: member?.computer_name || '',
                        area_name: member?.area_name || '',
                        upmachine_time: member?.upmachine_time ? member.upmachine_time : ''
                    })
                }
            })

            await t.commit()
            flag = 5
            return results
        } catch (error) {
            await t.rollback() // 回滚

            if (error?.original?.sqlMessage) {
                logger.error(`同步在线会员失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${error?.original?.sqlMessage}`)
                helper.failed(1001, null, error?.original?.sqlMessage)
            } else if (error?.errors) {
                logger.error(`同步在线会员失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${JSON.stringify(error.errors)}`)
                helper.failed(1001, null, JSON.stringify(error.errors))
            } else {
                logger.error(`同步在线会员失败   flag:[${flag}] pid:[${params.pid}] mid:[${params.mid}] ${JSON.stringify(error)}`)
                helper.failed(1001, null, JSON.stringify(error))
            }

            return false
        }
    }
}

module.exports = OnlineMemberService
